package authHeader

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"roomAdmin/models/authModel"
	"roomAdmin/service/authService"
	"roomAdmin/utils/errmsg"
	"roomAdmin/utils/jwt"
)

func Login(c *gin.Context) {
	var login authModel.LoginMsg
	var err 	error
	var tokenStr string

	// 绑定参数
	err = c.ShouldBind(&login)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":	errmsg.ParamTypeBindErrorCode,
			"message": errmsg.ParamTypeBindErrorMsg,
		})
		return
	}

	// 密码校验
	sign, role, err := authService.Login(login)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":	errmsg.SelectOperationFailCode,
			"message": errmsg.SelectOperationFailMsg,
		})
		return
	}

	// 用户不存在或密码不正确
	if !sign {
		c.JSON(http.StatusOK, gin.H{
			"code":	errmsg.LoginFailCode,
			"message": errmsg.LoginFailMsg,
		})
		return
	}

	// 生成Token
	tokenStr, _ = jwt.GenToken(login.UserName, role)

	c.JSON(http.StatusOK, gin.H{
		"code":	errmsg.SuccessCode,
		"message": errmsg.SuccessMsg,
		"data":	gin.H{
			"token": tokenStr,
		},
	})
}